package com.faithbj.controller.infoInput;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.model.*;
import com.faithbj.common.model.Dictionary;
import com.faithbj.common.model.fm.FamilyMember;
import com.faithbj.common.model.fm.FamilyMemberIncome;
import com.faithbj.common.model.fm.property.*;
import com.faithbj.common.service.RegionService;
import com.faithbj.common.utils.CommonUtil;
import com.faithbj.common.utils.DictionaryUtil;
import com.faithbj.common.utils.JsonUtil;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.process.ProcessApplicationService;
import com.faithbj.process.State;
import com.faithbj.process.TaskModel;
import com.faithbj.process.stats.VerifyReason;
import com.faithbj.service.CheckTotalService;
import com.faithbj.service.FamilyMemberPropertyService;
import com.faithbj.service.FamilyMemberService;
import com.faithbj.support.updownload.FileNamingStragegy;
import com.faithbj.support.updownload.FileUploadHandler;
import com.faithbj.support.updownload.FileUploadHandlerSaveToLocalDisk;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//import com.faithbj.common.model.dto.Deposit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/infoInput")
public class InfoInputController extends BaseController {

	private static final long serialVersionUID = 9068281894134828427L;

	private final Logger logger = LoggerFactory
			.getLogger(InfoInputController.class);

	@Resource
	private CheckTotalService checkTotalService;
	@Resource
	private FamilyMemberService familyMemberService;
	@Resource
	private FamilyMemberPropertyService familyMemberPropertyService;
	@Resource
	private RegionService regionService;
	@Resource
	private DictionaryUtil dictionaryUtil;
	@Resource
	private ProcessApplicationService processApplicationService;

	@Resource
	private FileUploadHandler FileUploadHandler;
	@Resource
	private FileNamingStragegy fileNamingStragegy;

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	@InitBinder
	@Override
	public void initBinder(WebDataBinder binder) {
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}

	@RequestMapping(value = "/index")
	public String list(Pager pager, ModelMap map) {
		List<TaskModel> tasks = processApplicationService
				.listAvailableTasksWithContentByUserAndState(State.COMPLETION,
						pager.getFirstResult(), pager.getPageSize());
		pager.setResult(tasks);
		pager.setTotalCount(processApplicationService
				.countAvailableTasksByUserAndState(State.COMPLETION));
		map.put("pager", pager);
		return "/infoInput/index";
	}

	@RequestMapping(value = "/searchPage")
	public String getSearchPage() {
		return "/infoInput/search";
	}

	@RequestMapping(value = "/familyBasicInfo/{id}/{taskId}/{result}")
	public String getCheckTotalById(@PathVariable("id") String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {

		CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		Set<FamilyMember> members = checkTotal.getFamilyMembers();
		for (FamilyMember fm : members) {
			if (fm.getMainApplicant()) {
				map.put("fm", fm);
			}
		}
		getDictionaryData(map);//字典数据
		map.put("taskId", taskId);// taskid，还要再传回去!要命啊！
		map.put("result", result.toString());// result，还要再传回去!要命啊！

		map.put("checkTotal", checkTotal);
		return "/infoInput/familyBasic";
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyBasicInfo", method = RequestMethod.POST)
	public ModelMap updateFamilyBasicInfo(CheckTotal ct) {
		ModelMap map = new ModelMap();
		// 主家庭成员
		FamilyMember member=familyMemberService.getFamilyMemberById(ct.getFamilyMember().getId());
		String[] excludeFmProperties={"checkTotal","country","marriedDate","settleTime","settleCountyTime", "workUnit",
				 "mainApplicant","relationMainApplicant","contactAddress","income","isReportDPI","isReportProperty","enclosure"};
		BeanUtils.copyProperties(ct.getFamilyMember(), member,excludeFmProperties);
		CheckTotal checkPO = checkTotalService.getCheckTotalById(ct.getId());//从数据库获取CheckTotal
		for(FamilyMember fm:checkPO.getFamilyMembers())
		{
			if(fm.getMainApplicant())
				fm=member;
		}
		
		checkPO.setEntrustInfo(ct.getEntrustInfo());
		checkPO.setDateApprovedProperty(ct.getDateApprovedProperty());
		checkPO.setEvenProperty(ct.getEvenProperty());
		checkPO.setStartDateApprovedIncome(ct.getStartDateApprovedIncome());
		checkPO.setEndDateApprovedIncome(ct.getEndDateApprovedIncome());
		checkPO.setEvenAvailableIncome(ct.getEvenAvailableIncome());
		checkTotalService.updateCheckTotal(checkPO);
		
		map.put("result", true);
		return map;
	}

	@RequestMapping(value = "/familyMemberInfo/{id}/{taskId}/{result}")
	public String getFamilyMembers(@PathVariable String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);
		getDictionaryData(map);
		map.put("checkTotalId", id);

		// 获取家庭主申请人的证明材料列表
		for (FamilyMember fms : familyMembers) {
			if (fms.getMainApplicant())
				map.put("enclosurelist", fms.getEnclosures());
			map.put("mainfm", fms);
		}

		return "/infoInput/familyMember";
	}


	@ResponseBody
	@RequestMapping(value = "/deleteFamilyMemberInfo/{id}")
	public Map deleteFamilyMemberInfo(@PathVariable String id) {
		Map map = new HashMap();
		try {
			FamilyMember fm = familyMemberService.getFamilyMemberById(id);
			if (fm != null) {
				familyMemberService.deleteFamilyMemberInfo(id);
			}
			map.put("result", true);
		} catch (Exception e) {
			logger.error("删除家庭成员出错", e);
			map.put("result", false);
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyMemberInfo", method = RequestMethod.POST)
	public Map updateFamilyMember(HttpServletRequest request) {
		Map map = new HashMap();
		FamilyMember fm = null;
		try {
			String checkTotalId = request.getParameter("checkTotalId");
			CheckTotal ct = checkTotalService.getCheckTotalById(checkTotalId);

			String familyMemberId = request.getParameter("familyMemberId");
			if (familyMemberId == null || familyMemberId.equals("")) {
				fm = new FamilyMember();
				fm.setCheckTotal(ct);
			} else {
				fm = familyMemberService.getFamilyMemberById(familyMemberId);
			}
			fm.setIdType(request.getParameter("familyMemberIdType"));
			fm.setIdNumber(request.getParameter("familyMemberIdNumber"));
			fm.setName(request.getParameter("familyMemberName"));
			fm.setGender(request.getParameter("familyMemberGender"));
			fm.setNation(request.getParameter("familyMemberNation"));
			String birthdayString = request
					.getParameter("familyMemberBirthday");
			fm.setBirthday(dateFormat.parse(birthdayString));
			fm.setPoliticalStatus(request
					.getParameter("familyMemberPoliticalStatus"));
			fm.setMaritalStatus(request
					.getParameter("familyMemberMaritalStatus"));
			fm.setPhone(request.getParameter("familyMemberPhone"));
			fm.setMobile(request.getParameter("familyMemberMobile"));
			fm.setZipCode(request.getParameter("familyMemberZip"));
			fm.setHouseholdDistrictCode(request
					.getParameter("familyMemberHouseholdDistrictCode"));
			fm.setHouseholdType(request
					.getParameter("familyMemberHouseholdType"));
			fm.setLivingDistrictCode(request
					.getParameter("familyMemberLivingDistrictCode"));
			fm.setLivingAddress(request
					.getParameter("familyMemberLivingAddress"));
			String startDateLivingString = request
					.getParameter("familyMemberStartDateLiving");
			fm.setStartDateLiving(dateFormat.parse(startDateLivingString));
			fm.setEducation(request.getParameter("familyMemberEducation"));
			fm.setHealthStatus(request.getParameter("familyMemberHealthStatus"));
			fm.setLaborLossStatus(request
					.getParameter("familyMemberLaborLossStatus"));
			fm.setDisabilityDegree(request
					.getParameter("familyMemberDisabilityDegree"));
			fm.setDiseaseName(request.getParameter("familyMemberDiseaseName"));
			if (fm.getMainApplicant() == null || !fm.getMainApplicant()) {
				fm.setMainApplicant(false);
			}
			fm.setRelationMainApplicant(request
					.getParameter("familyMemberRelationMainApplicant"));
			familyMemberService.saveFamilyMember(fm);
			map.put("result", true);
		} catch (Exception e) {
			logger.error("更新家庭成员出错", e);
			map.put("result", false);
		}
		return map;
	}

	@RequestMapping(value = "/familyMemberIncome/{id}/{taskId}/{result}")
	public String getFamilyMemberIncomes(@PathVariable String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		CheckTotal ct = checkTotalService.getCheckTotalById(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotal", ct);
		return "/infoInput/memberIncome";
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyMemberIncome", method = RequestMethod.POST)
	public Map updateFamilyMemberIncome(FamilyMemberIncome memberIncome,String checkTotalId,String familyMemberId,
			String startDateApprovedIncomeString,Date startDateApprovedIncome,Date endDateApprovedIncome) {
		Map map = new HashMap();

		CheckTotal ct = checkTotalService.getCheckTotalById(checkTotalId);

		ct.setStartDateApprovedIncome(startDateApprovedIncome);
		ct.setEndDateApprovedIncome(endDateApprovedIncome);

		FamilyMember fm = familyMemberService.getFamilyMemberById(familyMemberId);
		if (fm != null) {
			fm.setIncome(memberIncome);
			familyMemberService.saveFamilyMember(fm);
			map.put("result", true);
		}
		else 
		{
			// TODO 跳转错误页面
			map.put("result", false);
			logger.error("更新家庭成员收入出错");
		}
		return map;
	}
	
	
	
	//获取公共字典方法
	private void getDictionaryData(ModelMap map) {
		List<Dictionary> types = dictionaryUtil.getListByTypeName("业务类型");
		List<Dictionary> idTypes = dictionaryUtil.getListByTypeName("证件类型");
		List<Dictionary> nations = dictionaryUtil.getListByTypeName("民族");
		List<Dictionary> politicalStatusList = dictionaryUtil.getListByTypeName("政治面貌");
		List<Dictionary> education = dictionaryUtil.getListByTypeName("文化程度");
		List<Dictionary> laborlost = dictionaryUtil.getListByTypeName("丧劳情况");
		List<Dictionary> maritalStatusList = dictionaryUtil.getListByTypeName("婚姻状况");
		List<Dictionary> householdTypeList = dictionaryUtil.getListByTypeName("户籍类型");
		List<Dictionary> disabilityDegreeList = dictionaryUtil.getListByTypeName("残疾等级");
		List<Dictionary> relaitionList = dictionaryUtil.getListByTypeName("与申请人代表关系");
		List<Dictionary> enclosures = dictionaryUtil.getListByTypeName("基本证明材料");
		List<Region> citys = regionService.getRegionListByType(Region.COUNTRY);
		List<Region> streets = regionService.getRegionListByType(Region.STREET);
		map.put("types", types);
		map.put("idTypes", idTypes);
		map.put("nations", nations);
		map.put("politicalStatusList", politicalStatusList);
		map.put("educations", education);
		map.put("laborlost", laborlost);
		map.put("maritalStatusList", maritalStatusList);
		map.put("householdTypes", householdTypeList);
		map.put("disabilityDegreeList", disabilityDegreeList);
		map.put("relaitionList", relaitionList);
		map.put("enclosures", enclosures);	
		map.put("citys", citys);
		map.put("streets", streets);
	}

	@RequestMapping(value = "/familyMemberProperty/{id}/{taskId}/{result}")
	public String getFamilyMemberProperties(@PathVariable("id") String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());// taskid，还要再传回去!要命啊！

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotalId", id);
		return "/infoInput/memberProperty";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getFamilyMemberProperty/{fmId}")
	public FamilyMemberProperty getFamilyMemberProperty(@PathVariable("fmId") String fmId){
		FamilyMemberProperty fmp=familyMemberPropertyService.findPropertyByFmId(fmId);
		return fmp;
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyMemberProperties", method = RequestMethod.POST)
	public ModelMap updateFamilyMemberProperties(FamilyMemberProperty fmp) {
		ModelMap map = new ModelMap();
		familyMemberPropertyService.saveOrUpdate(fmp);
		map.put("result", true);
		return map;
	}

	/**
	 * 显示发送街镇核实页面
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/sendCheck/{id}/{taskId}/{result}")
	public String getFamilyMembersForSendCheck(@PathVariable String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);

		// 获取主申请人信息
		FamilyMember mainApply = null;
		for (FamilyMember fm : familyMembers) {
			if (fm.getMainApplicant())
				mainApply = fm;
		}
		// 获取登录用户实际姓名
		String username = getLoginUser().getName();

		map.put("familyMembers", familyMembers);
		map.put("mainApply", mainApply);
		map.put("username", username);

		map.put("checkTotalId", id);
		map.put("taskId", taskId);
		map.put("result", result.toString());
		return "/infoInput/sendCheck";
	}

	/**
	 * 发送信息核实
	 * 
	 */

	@RequestMapping(value = "/sendCheck", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap sendCheck(VerifyReason verifyReason, String checkTotalId, Long taskId) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", verifyReason.getName());
		CheckTotal checkTotal = checkTotalService
				.getCheckTotalById(checkTotalId);
//		map.put("excludedForVerify", principal.getName()); // not needed since tasks are now assigned in order.
		processApplicationService.completeTask(taskId, checkTotal, map);

		ModelMap mMap = new ModelMap();
		mMap.put("status", "1");// 跳转到基本信息页

		return mMap;
		// return "redirect:/infoverify/index";
	}

	/**
	 * 上传证明材料列
	 */
	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ModelMap listEnclosures(MultipartFile upfile, Enclosure enclosure,
			String fmId) {
		ModelMap map = new ModelMap();

		if (upfile.getSize() > 0) {
			Map<Integer, String> checkResult = FileUploadHandler
					.checkFileExtention(upfile);
			for (Integer relt : checkResult.keySet()) {
				if (!FileUploadHandlerSaveToLocalDisk.UPLOAD_PERMITION.equals(relt)) {// 说明验证没通过，返回错误
					map.put("status", 2);
					return map;
				}
			}

			enclosure.setId(CommonUtil.getUUID());// 生成id
			String filepath = fileNamingStragegy.getFilePath(upfile, fmId,
					enclosure.getId());
			FileUploadHandler.uploadByFilePath(upfile, filepath);

			FamilyMember member = familyMemberService.getFamilyMemberById(fmId);

			enclosure.setPath(filepath);

			List<Enclosure> list = member.getEnclosures();
			list.add(enclosure);

			member.setEnclosure(JsonUtil.toJson(list));
			familyMemberService.updateFamilyMember(member);

			map.put("status", 1);
			map.put("enclosure", enclosure);
			return map;
		}
		// 文件大小为0，说明是空文件
		map.put("status", 2);
		return map;
	}

	/**
	 * 上传证明材料删除
	 */
	@ResponseBody
	@RequestMapping(value = "/delete/{fmId}/{id}")
	public ModelMap listEnclosures(@PathVariable("fmId") String fmId,
			@PathVariable("id") String id) {
		ModelMap map = new ModelMap();

		FamilyMember member = familyMemberService.getFamilyMemberById(fmId);

		List<Enclosure> list = member.getEnclosures();
		// 解开json，更新
		for (int i = 0; i < list.size(); i++) {
			if (StringUtils.equals(list.get(i).getId(), id)) {
				FileUtils.deleteQuietly(new File(list.get(i).getPath()));
				logger.error("删除上传证明材料！");
				list.remove(i);
				break;
			}
		}

		member.setEnclosure(JsonUtil.toJson(list));
		familyMemberService.updateFamilyMember(member);
		map.put("status", 1);

		return map;
	}


}
